#include "mysql_friend_request.h"

#include "friend_request-odb.hxx"
#include "log.h"

namespace chat {
bool FriendRequestTable::insert(FriendRequest& friend_request) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->persist(friend_request);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("新增好友申请[{}->{}]失败: {}", friend_request.user_id(),
                  friend_request.peer_id(), e.what());

        return false;
    }

    return true;
}
bool FriendRequestTable::remove(const std::string& user_id,
                              const std::string& peer_id) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->erase_query<FriendRequest>(
            odb::query<FriendRequest>::user_id == user_id &&
            odb::query<FriendRequest>::peer_id == peer_id);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("删除好友申请[{}->{}]失败: {}", user_id, peer_id, e.what());

        return false;
    }

    return true;
}

bool FriendRequestTable::exists(const std::string& user_id,
                              const std::string& peer_id) {
    bool ret = false;
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        odb::result<FriendRequest> r = db_->query<FriendRequest>(
            odb::query<FriendRequest>::user_id == user_id &&
            odb::query<FriendRequest>::peer_id == peer_id);

        ret = !r.empty();

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("查询好友申请[{}->{}]失败: {}", user_id, peer_id, e.what());

        return false;
    }

    return ret;
}

std::vector<std::string> FriendRequestTable::peers(const std::string& user_id) {
    std::vector<std::string> peers;
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        odb::result<FriendRequest> r = db_->query<FriendRequest>(
            odb::query<FriendRequest>::peer_id == user_id);
            
        for (auto &friend_request : r) {
            peers.push_back(friend_request.user_id());
        }

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("查询好友申请[{}]失败: {}", user_id, e.what());

        return peers;
    }

    return peers;
}
}  // namespace chat